package initialize

import (
	"fmt"

	_ "github.com/mbobakov/grpc-consul-resolver"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"mxshop-api/userop-web/global"
)

func InitSrvConn() (err error) {
	conf := global.ServerConfig

	// 建立userop service RPC连接
	global.UserOpConn, err = grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", conf.ConsulConfig.Host, conf.ConsulConfig.Port, conf.UserOpSrvConfig.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		return err
	}

	// 建立goods service RPC连接
	global.GoodsConn, err = grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", conf.ConsulConfig.Host, conf.ConsulConfig.Port, conf.GoodsSrvConfig.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		return err
	}

	return nil
}
